var model = require("../models");
var config     = require('../config');
var eventproxy = require('eventproxy');
var UserProxy  = require('../proxy').User;


exports.authUser = function (req, res, next) {
    var ep = new eventproxy();
    ep.fail(next);

    res.locals.current_user = null;


    ep.all('get_user', function (user) {
        if (!user) {
            return next();
        }
        user = res.locals.current_user = req.session.user = user;
    });

    if (config.debug && req.cookies['mock_user']) {
        var mockUser = JSON.parse(req.cookies['mock_user']);
        UserProxy.getUserByToken(mockUser,ep.done('get_user'));
    }


    if (req.session.user) {
        ep.emit('get_user', req.session.user);
    } else {
        var auth_token = req.headers["token"];
        if (!auth_token) {
            return next();
        }
        UserProxy.getUserByToken(auth_token,ep.done('get_user'));
    }
};
